﻿using SD.Infrastructure.Repository.EntityFramework;
using SD.Infrastructure.RepositoryBase;
using SD.OpcProxy.Domain.Entities;
using SD.OpcProxy.Domain.IRepositories;
using SD.OpcProxy.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SD.OpcProxy.Repository.Implements
{
    /// <summary>
    /// 变量仓储实现
    /// </summary>
    public class VariableRepository : EFAggRootRepositoryProvider<Variable>, IVariableRepository
    {
        #region # 分页获取变量列表 —— ICollection<Variable> FindByPage(string keywords, VariableType? variableType...
        /// <summary>
        /// 分页获取变量列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="variableType">变量类型</param>
        /// <param name="isReadonly">是否只读</param>
        /// <param name="dataTypes">数据类型集</param>
        /// <param name="opcServerId">OPC服务器Id</param>
        /// <param name="keepRecord">是否记录历史</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录条数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>变量列表</returns>
        public ICollection<Variable> FindByPage(string keywords, VariableType? variableType, bool? isReadonly, IList<string> dataTypes, Guid? opcServerId, bool? keepRecord, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<Variable, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords)) &&
                    (isReadonly == null || x.IsReadonly == isReadonly) &&
                    (variableType == null || x.VariableType == variableType) &&
                    (opcServerId == null || x.OpcServerId == opcServerId) &&
                    (keepRecord == null || x.KeepRecord == keepRecord);

            IQueryable<Variable> variables = base.Find(condition);

            if (dataTypes != null && dataTypes.Any())
            {
                variables = variables.Where(x => dataTypes.Contains(x.DataType));
            }

            IOrderedQueryable<Variable> orderedVariables = variables.OrderByDescending(x => x.AddedTime);

            return orderedVariables.ToPage(pageIndex, pageSize, out rowCount, out pageCount).ToList();
        }
        #endregion
    }
}
